/* eslint-disable consistent-return */
/* eslint-disable array-callback-return */
import React from 'react';
import { connect } from 'dva';
import { DownloadOutlined, DownOutlined, PlusOutlined, UpOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Table,
  Button,
  Modal,
  Input,
  Select,
  Row,
  Col,
  message,
  Badge,
  Divider,
  Menu,
  Dropdown,
} from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import downloadFile from '@/utils/utils';
import { checkPermissions } from '@/utils/authority';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';
import HOCSelect from '@/components/AntDesign/Select';
import Customer from '../../components/Customer'; // 客户名称字典
import Quotation from '../../components/Quotation'; // 报价单字典
import Contract from '../../components/Contract'; // 商务合同名称字典
import Supplier from '../../components/Supplier'; // 获取字典签约方
import TextOverFlow from '../../components/TextOverFlow';

const FormItem = Form.Item;
const { Option } = Select;
const { confirm } = Modal;

@connect(({ publicdata, quotation, loading }) => ({
  dictCode: publicdata.dictCode,
  pageData: quotation.pageData,
  loading: loading.models.quotation,
  formFieldsValue: quotation.formFieldsValue,
  expandForm: quotation.expandForm,
  valuesArr: quotation.valuesArr,
  respUserList: quotation.respUserList,
}))
@Form.create()
class BasicList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      formValues: {},
      selectedRows: [],
      selectedRowKeys: [],
      quoStatusList: [], // 报价单状态
    };
    // 表单布局
    this.formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
  }

  componentDidMount() {
    const {
      dispatch,
    } = this.props;
    // 修改的清空值
    dispatch({
      type: 'quoupdate/updateModelData',
      payload: { isGoBack: false },
    });

    // 获取字典状态
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['SER_TYPE', 'COMMON_ENABLED_STATUS'],
    }).then(dictCode => {
      const sortNumber = (a, b) => a.itemCode - b.itemCode;
      dictCode.COMMON_ENABLED_STATUS.map(status => {
        const temp = status;
        switch (status.itemCode) {
          case '1':
            temp.statusStyle = 'default'; // 待启用
            break;
          case '2':
            temp.statusStyle = 'success'; // 已启用
            break;
          case '3':
            temp.statusStyle = 'error'; // 已停用
            break;
          default:
            temp.statusStyle = '';
        }
        return true;
      });
      this.setState({ quoStatusList: dictCode.COMMON_ENABLED_STATUS.sort(sortNumber) });
    });
    // 获取所属客服列表数据
    dispatch({
      type: 'quotation/fetchRespUserList',
      payload: {},
    });
    this.getInitialList();
  }

  getInitialList = () => {
    const {
      pageData: { pagination },
      dispatch,
      location,
      formFieldsValue,
    } = this.props;
    if (location.queryParam) {
      dispatch({
        type: 'quotation/updateModelData',
        payload: { formFieldsValue: location.queryParam, expandForm: true },
      });
    }

    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = () => {
    const { form, valuesArr, dispatch } = this.props;
    form.validateFieldsAndScroll([...valuesArr], (err, values) => {
      if (!err) {
        dispatch({
          type: 'quotation/updateModelData',
          payload: {
            formFieldsValue: values,
          },
        });
        this.searchList(this.processFormData(values));
      }
    });
  };

  // 查询
  searchList = (
    formFieldsValue,
    currentPage = 1,
    pageSize = 10,
    isClear = true,
  ) => {
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }
    const { dispatch } = this.props;
    const pageArg = { currentPage, pageSize };
    const values = {
      ...formFieldsValue,
      pageArg,
    };

    dispatch({
      type: 'quotation/updateModelData',
      payload: {
        values,
      },
    });

    dispatch({
      type: 'quotation/fetchList',
      payload: values,
    });

    this.setState({
      formValues: formFieldsValue,
    });
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'quoNo') {
        tempFieldsValue[key] = (tempFieldsValue[key] && tempFieldsValue[key].trim()) || null;
      }
      formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
    });
    return formFieldsValue;
  };

  // 切换表格展开收起
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'quotation/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  // 重置
  resetSearch = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'quotation/updateModelData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
  };

  // 新增报价单
  addBao = () => {
    const { dispatch } = this.props;
    localStorage.custId789 = null;
    dispatch({
      type: 'quotation/updateQuery',
      payload: {
        sendSuppId: undefined, // 签约方
        custId: undefined, // 客户名称
        contId: undefined, // 供应商合同
        custContId: undefined,
        quoName: undefined, // 报价单名称
        pdId: undefined, // 产品id
        serType: undefined, // 服务类型
        taxRatio: '0.001', // 填写的税率
      },
    });
    router.push('/salemanage/quotation/add');
  };

  // 查看
  toDetail = (e, record) => {
    router.push(`/salemanage/quotation/detail?quoId=${record}`);
  };

  // 修改
  update = (e, record) => {
    router.push(`/salemanage/quotation/update?quoId=${record.quoId}&quoState=${record.quoState}`);
  };

  // 删除
  delList = quoId => {
    this.setState({ selectedRowKeys: [quoId] });
    const {
      pageData: { pagination },
      dispatch,
      formFieldsValue,
    } = this.props;
    confirm({
      icon: <QuestionCircleOutlined />,
      title: '您确定要删除吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'quotation/deleteData',
          payload: { quoId },
        }).then(res => {
          if (res.success) {
            message.success('删除成功！');
            this.searchList(this.processFormData(formFieldsValue), pagination.current, pagination.pageSize);
          } else {
            message.warning(`${res.message || '删除失败！'}`);
            this.setState({ selectedRowKeys: [] });
          }
        });
      },
      onCancel: () => {
        this.setState({ selectedRowKeys: [] });
      },
    });
  };

  // 待启用-启用状态
  ableStatus = (quoId, flag) => {
    this.setState({ selectedRowKeys: [quoId] });
    const quoState = flag === 1 ? 2 : 1;
    const {
      pageData: { pagination },
      dispatch,
      formFieldsValue,
    } = this.props;
    confirm({
      icon: <QuestionCircleOutlined />,
      title: `你确定要${quoState === 2 ? '启用' : '停用'}吗？`,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'quotation/changeState',
          payload: { quoId, quoState },
        }).then(res => {
          if (res.success) {
            message.success(`${res.message || '启用成功！'}`);
            this.searchList(this.processFormData(formFieldsValue), pagination.current, pagination.pageSize);
            this.setState({ selectedRowKeys: [] });
          } else {
            message.warning(`${res.message || '启用失败！'}`);
          }
        });
      },
      onCancel: () => {
        this.setState({ selectedRowKeys: [] });
      },
    });
  };

  // 停用-启用状态
  stopstartStatus = (quoId, flag) => {
    this.setState({ selectedRowKeys: [quoId] });
    const quoState = flag === 3 ? 2 : 3;
    const {
      pageData: { pagination },
      dispatch,
      formFieldsValue,
    } = this.props;
    confirm({
      icon: <QuestionCircleOutlined />,
      title: `你确定要${quoState === 2 ? '启用' : '停用'}吗？`,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'quotation/changeState',
          payload: { quoId, quoState },
        }).then(res => {
          if (res.success) {
            message.success(`${res.message || '启用成功！'}`);
            this.searchList(this.processFormData(formFieldsValue), pagination.current, pagination.pageSize);
            this.setState({ selectedRowKeys: [] });
          } else {
            message.warning(`${res.message || '启用失败！'}`);
          }
        });
      },
      onCancel: () => {
        this.setState({ selectedRowKeys: [] });
      },
    });
  };

  // 已启用-停用状态
  updateStatus = (quoId, flag) => {
    this.setState({ selectedRowKeys: [quoId] });
    const quoState = flag === 2 ? 3 : 1;
    const {
      pageData: { pagination },
      dispatch,
      formFieldsValue,
    } = this.props;
    confirm({
      icon: <QuestionCircleOutlined />,
      title: `你确定要${quoState === 3 ? '停用' : '启用'}吗？`,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'quotation/changeState',
          payload: { quoId, quoState },
        }).then(res => {
          if (res.success) {
            message.success(`${res.message || '停用成功！'}`);
            this.searchList(this.processFormData(formFieldsValue), pagination.current, pagination.pageSize);
            this.setState({ selectedRowKeys: [] });
          } else {
            message.warning(`${res.message || '停用失败！'}`);
          }
        });
      },
      onCancel: () => {
        this.setState({ selectedRowKeys: [] });
      },
    });
  };

  // 导出数据
  export = () => {
    const { selectedRowKeys } = this.state;
    if (!selectedRowKeys.length) {
      Modal.confirm({
        icon: <QuestionCircleOutlined />,
        title: '温馨提示',
        content: '如果不选择列表数据，则默认导出当前条件下所有数据',
        okText: '导出',
        cancelText: '取消',
        onOk: () => {
          this.exportExcel();
        },
      });
    } else {
      this.exportExcel();
    }
  };

  // 导出excel
  exportExcel = () => {
    const { formValues, selectedRowKeys } = this.state;
    const params = {
      ...formValues,
      quoList: selectedRowKeys,
    };
    downloadFile(params, '/csApi/crmquo/exportExcel', 'POST');
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="客户名称">
              {getFieldDecorator('custId', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.custId,
              })(<Customer allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="报价单名称">
              {getFieldDecorator('quoId', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.quoId,
              })(<Quotation allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={this.searchBtnList}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
      dictCode,
      respUserList,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="客户名称">
              {getFieldDecorator('custId', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.custId,
              })(<Customer allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="报价单名称">
              {getFieldDecorator('quoId', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.quoId,
              })(<Quotation allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="合同名称">
              {getFieldDecorator('custContId', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.custContId,
              })(<Contract params={{ contType: 3 }} allowClear />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="报价单编号">
              {getFieldDecorator('quoNo', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.quoNo,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="报价单状态">
              {getFieldDecorator('quoState', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.quoState,
              })(
                <HOCSelect
                  placeholder="请输入关键字检索"
                  allowClear
                  showSearch
                  optionFilterProp="children"
                >
                  {dictCode &&
                    dictCode.COMMON_ENABLED_STATUS.map(item => (
                      <Option key={item.itemCode}>{item.itemName}</Option>
                    ))}
                </HOCSelect>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="签约方">
              {getFieldDecorator('suppId', {
                initialValue: formFieldsValue.suppId,
                rules: [{ required: false }],
              })(<Supplier allowClear />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="所属客服" {...this.formItemLayout}>
              {getFieldDecorator('primId', {
                rules: [{ required: false, message: '请选择' }],
                initialValue: formFieldsValue.primId,
              })(
                <HOCSelect
                  placeholder="请输入关键字检索"
                  style={{ width: '100%' }}
                  showSearch
                  optionFilterProp="children"
                  allowClear
                >
                  {respUserList.map(item => (
                    <Option key={item.userId} title={item.userName}>
                      {item.userName}
                    </Option>
                  ))}
                </HOCSelect>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span className={styles.submitButtons} style={{ float: 'right' }}>
                <Button type="primary" onClick={this.searchBtnList}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起 <UpOutlined />
                </a>
              </span>
            </div>
          </Col>
        </Row>

      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const { selectedRowKeys, quoStatusList, selectedRows } = this.state;
    const { pageData, loading, formFieldsValue } = this.props;
    const total = pageData && pageData.pagination.total;
    // 表格配置：行选择
    const rowSelection = {
      selectedRowKeys,
      onChange: (rows) => {
        this.setState({ selectedRowKeys: rows, selectedRows });
      },
    };
    // 表格配置：分页器
    const pagination = {
      defaultCurrent: pageData.pagination.current,
      defaultPageSize: pageData.pagination.pageSize, // 默认单页条数
      current: pageData.pagination.current, // 当前页
      pageSize: pageData.pagination.pageSize, // 单页条数
      total, // 数据总数
      showQuickJumper: true, // 跳转至某页
      showSizeChanger: true, // 是否可以改变 pageSize
      onChange: (page, pageSize) => {
        // 页码改变的回调
        this.searchList(this.processFormData(formFieldsValue), page, pageSize);
      },
      onShowSizeChange: (current, size) => {
        // 单页条数变化的回调
        this.searchList(this.processFormData(formFieldsValue), current, size);
      },
      showTotal: totals => {
        const totalPage =
          totals < pagination.pageSize ? 1 : Math.ceil(totals / pagination.pageSize);
        return `共 ${totals} 条记录 第 ${pagination.current} / ${totalPage}页`;
      },
    };
    // 表格
    const columns = [
      {
        title: '报价单编号',
        dataIndex: 'quoNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '报价单名称',
        dataIndex: 'quoName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '合同名称',
        dataIndex: 'contName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '签约方',
        dataIndex: 'suppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '状态',
        dataIndex: 'quoState',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: val =>
          (val &&
            quoStatusList.map(status => {
              if (Number(status.itemCode) === val) {
                return (
                  <Badge key={status.itemCode} status={status.statusStyle} text={status.itemName} />
                );
              }
            })) ||
          '--',
      },
      {
        title: '所属客服',
        dataIndex: 'primName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val && val || '--',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => {
          if (record.quoState === 1) {
            return (
              <span>
                {checkPermissions('cs:crmquo:updateStatus') && (
                  <a onClick={() => this.ableStatus(record.quoId, record.quoState)}>启用</a>
                )}
                <Divider type="vertical" />
                <Dropdown
                  overlay={
                    <Menu>
                      <Menu.Item key="look" onClick={e => this.toDetail(e, record.quoId)}>
                        查看
                      </Menu.Item>
                      {checkPermissions('cs:crmquo:update') && (
                        <Menu.Item key="update" onClick={e => this.update(e, record)}>
                          修改
                        </Menu.Item>
                      )}
                      {checkPermissions('cs:crmquo:deleteMul') && (
                        <Menu.Item key="delete" onClick={() => this.delList(record.quoId)}>
                          删除
                        </Menu.Item>
                      )}
                    </Menu>
                  }
                >
                  <a>
                    更多 <DownOutlined />
                  </a>
                </Dropdown>
              </span>
            );
          }
          if (record.quoState === 2) {
            return (
              <span>
                <a onClick={e => this.toDetail(e, record.quoId)}>查看</a>
                {checkPermissions('cs:crmquo:updateStatus') && <Divider type="vertical" />}
                {/* {checkPermissions('cs:crmquo:updateStatus') && (
                  <a onClick={e => this.updateStatus(record.quoId, record.quoState)}>停用</a>
                )} */}
                <Dropdown
                  overlay={
                    <Menu>
                      {checkPermissions('cs:crmquo:update') && (
                        <Menu.Item key="update" onClick={e => this.update(e, record)}>
                          修改
                        </Menu.Item>
                      )}
                      {checkPermissions('cs:crmquo:updateStatus') && (
                        <Menu.Item onClick={() => this.updateStatus(record.quoId, record.quoState)}>
                          停用
                        </Menu.Item>
                      )}
                    </Menu>
                  }
                >
                  <a>
                    更多 <DownOutlined />
                  </a>
                </Dropdown>
              </span>
            );
          }
          if (record.quoState === 3) {
            return (
              <span>
                <a onClick={e => this.toDetail(e, record.quoId)}>查看</a>
                {checkPermissions('cs:crmquo:updateStatus') && <Divider type="vertical" />}
                {checkPermissions('cs:crmquo:updateStatus') && (
                  <a onClick={() => this.stopstartStatus(record.quoId, record.quoState)}>启用</a>
                )}
              </span>
            );
          }
          if (!record.quoState) {
            return <a onClick={e => this.toDetail(e, record.quoId)}>查看</a>;
          }
        },
      },
    ];
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card className={styles.tableCard}>
          <Row style={{ marginBottom: 16 }}>
            <Authorized authority="cs:crmquo:insert" noMatch={null}>
              <Button type="primary" style={{ marginRight: 8 }} onClick={this.addBao}>
                <PlusOutlined />
                新增
              </Button>
            </Authorized>
            <Authorized authority="cs:crmquo:uploadQuoOut" noMatch={null}>
              <Button
                style={{ marginRight: 8 }}
                onClick={() => router.push(`/salemanage/quotation/batchadd`)}
              >
                批量新增
              </Button>
            </Authorized>
            <Authorized authority="cs:crmquo:getList" noMatch={null}>
              <Button onClick={this.export}>
                <DownloadOutlined />
                导出
              </Button>
            </Authorized>
          </Row>
          <Table
            rowSelection={rowSelection}
            dataSource={pageData && pageData.list}
            columns={columns}
            rowKey={record => record.quoId}
            loading={loading}
            pagination={pagination}
            style={{ backgroundColor: '#fff', textaAlign: 'center' }}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}
const ListSearchForm = Form.create()(BasicList);
export default ListSearchForm;
